#!/bin/sh
set -e
set -x

[ ! -d /root/.ethereum/geth/chaindata ] && geth init /config/genesis.json

HOSTNAME=`hostname -i`
[ $RPC ] && RPCOPT="--rpc --rpcaddr 0.0.0.0 --rpcport 8545 --rpcapi eth,net,web3,admin,personal"

[ $WS ] && WSOPT="--ws --wsaddr 0.0.0.0"

[ $SINGER ] && MINE="--mine --etherbase $ACCOUNT --unlock 0x$ACCOUNT --password /config/password"

[ $NETWORKID ] && NETWORK="--networkid $NETWORKID"

ENODE=`bootnode --nodekey=/bootnode_keys/boot.key -writeaddress`
#BOOTNODEIP=`getent hosts bootnode | awk '{ print $1 }'`


while true
do
  BOOTNODEIP=`ping -c 1 bootnode|awk -F '[()]' 'NR==1{print $2}'`
  if [ ! -z $BOOTNODEIP ];then
    break
  fi
done

BOOTNODEIP=`ping -c 1 bootnode|awk -F '[()]' 'NR==1{print $2}'`
ipnum=0
ip2num() {
     local ip=$1
     local a=$(echo $ip | awk -F '.' '{print $1}')
     local b=$(echo $ip | awk -F '.' '{print $2}')
     local c=$(echo $ip | awk -F '.' '{print $3}')
     local d=$(echo $ip | awk -F '.' '{print $4}')

     #echo "$(( (a<<24)+(b<<16)+(c<<8)+d ))"
     ipnum="$(( (a<<24)+(b<<16)+(c<<8)+d ))"
     echo ${ipnum}

}
ip2num $BOOTNODEIP
newipnum=`expr ${ipnum} + 1`

newip=0
num2ip() {
     local num=$1
     local a=$((num>>24))
     local b=$((num>>16&0xff))
     local c=$((num>>8&0xff))
     local d=$((num&0xff))
     newip="$a.$b.$c.$d"
 }
num2ip $newipnum

#BOOTNODEIP=`getent hosts bootnode | awk '{ print $1 }'`
#BOOTNODE="--bootnodes enode://$ENODE@$BOOTNODEIP:30301"
BOOTNODE="--bootnodes enode://$ENODE@[$newip]:30301"


KEYSTORE=/root/.ethereum/
cp -r /config/keystore $KEYSTORE
sleep 5
geth $RPCOPT --rpccorsdomain "*" $WSOPT $MINE $NETWORK $BOOTNODE --verbosity $LOGGING_LEVEL
echo "===============> geth $RPCOPT --rpccorsdomain "*" $WSOPT $MINE $NETWORK $BOOTNODE --verbosity $LOGGING_LEVEL ================"
echo "--------------------->bootnode ip = $newip =================="
